package com.atguigu.gulimail.ware.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.utils.R;
import com.atguigu.gulimail.ware.entity.Vo.FareVo;
import com.atguigu.gulimail.ware.entity.Vo.MemberAddressVo;
import com.atguigu.gulimail.ware.feign.MemberFeignService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimail.ware.dao.WareInfoDao;
import com.atguigu.gulimail.ware.entity.WareInfoEntity;
import com.atguigu.gulimail.ware.service.WareInfoService;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                new QueryWrapper<WareInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageCondtion(Map<String, Object> params) {

        LambdaQueryWrapper<WareInfoEntity> wrapper=new LambdaQueryWrapper<>();
        String key=(String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.like(WareInfoEntity::getName,key);
            wrapper.or().eq(WareInfoEntity::getId,key);
            wrapper.or().like(WareInfoEntity::getAddress,key);
        }

        IPage<WareInfoEntity> iPage=this.page(new Query<WareInfoEntity>().getPage(params),wrapper);
        return new PageUtils(iPage);
    }

    @Override
    public FareVo getFare(Long addrId) {

        FareVo fareVo = new FareVo();

        R info = memberFeignService.info(addrId);
        String jsonString = JSON.toJSONString(info.get("memberReceiveAddress"));
        MemberAddressVo memberAddressVo = JSON.parseObject(jsonString, MemberAddressVo.class);

        fareVo.setAddress(memberAddressVo);

        if(memberAddressVo!=null){
            int money = 10;
            fareVo.setFare(new BigDecimal(money));
            return fareVo;
        }

        return fareVo;
    }

}